package com.yc;

import dev.langchain4j.community.model.dashscope.QwenEmbeddingModel;
import dev.langchain4j.data.embedding.Embedding;
import dev.langchain4j.model.output.Response;

import java.util.List;


public class RAG_App1 {
    public static void main(String[] args) {
        QwenEmbeddingModel qwenEmbeddingModel = QwenEmbeddingModel.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .build();
        Response<Embedding> embed = qwenEmbeddingModel.embed("是");
        System.out.println(embed.content()); //向量值
        System.out.println(embed.content().vector().length); //向量长度 维度

        //1.相似度比较
        Embedding embed1 = qwenEmbeddingModel.embed("这是一只漂亮的小狗").content();
        double sim1 = cosineSimilarity(embed.content().vectorAsList(),embed1.vectorAsList());
        System.out.println("相似度："+sim1);
        Embedding embed2 = qwenEmbeddingModel.embed("这是一只漂亮的小猫").content();
        double sim2 = cosineSimilarity(embed.content().vectorAsList(),embed2.vectorAsList());
        System.out.println("相似度："+sim2);
        Embedding embed3 = qwenEmbeddingModel.embed("那是一条狗").content();
        double sim3 = cosineSimilarity(embed.content().vectorAsList(),embed3.vectorAsList());
        System.out.println("相似度："+sim3);
        Embedding embed4 = qwenEmbeddingModel.embed("否").content();
        double sim4 = cosineSimilarity(embed.content().vectorAsList(),embed4.vectorAsList());
        System.out.println("相似度："+sim4);
    }

    private static double cosineSimilarity(List<Float> a, List<Float> b) {
        if(a.size()!=b.size()){
            throw new IllegalArgumentException("向量长度不一致");
        }
        double dotProduct = 0.0;
        double normA = 0.0;
        double normB = 0.0;
        for(int i=0;i<a.size();i++){
            double x = a.get(i);
            double y = b.get(i);
            dotProduct += x*y;
            normA += x*x;
            normB += y*y;
        }
        if(normA==0 || normB==0){
            return 0.0;
        }
        return dotProduct/(Math.sqrt(normA)*Math.sqrt(normB));
    }
}
